#include <algorithm>
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
struct ListNode {
    int val;
    ListNode *next;
};
class Solution {
public:
    vector<int> nextLargerNodes(ListNode* head) {
        ListNode*prev=NULL;
        ListNode*cur=head;
        vector<int>ans;
        while(cur!=NULL){
            ListNode*tmp=cur->next;
            cur->next=prev;
            prev=cur;
            cur=tmp;
        }
        head=prev;
        stack<int>st;
        while(head)
        {
            if(st.empty())
            {
                ans.push_back(0);
                st.push(head->val);
            }
            else if(head->val<st.top())
            {
                ans.push_back(st.top());
                st.push(head->val);
            }
            else if(head->val>=st.top()){
                while(!st.empty())
                {
                    if(st.top()<=head->val)
                        st.pop();
                    else break;
                }
                if(st.empty())
                    ans.push_back(0);
                else
                    ans.push_back(st.top());
                st.push(head->val);
                }
            head=head->next;
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};